package com.medicine.hbp.ui;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;
import org.kymjs.kjframe.http.HttpParams;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.medicine.hbp.R;
import com.medicine.hbp.base.BaseActivity;
import com.medicine.hbp.dialog.DetailEditDialog;
import com.medicine.hbp.dialog.PayDialog;
import com.medicine.hbp.dialog.PayDialog.PayDialogListener;
import com.medicine.hbp.dialog.PhotographDialog;
import com.medicine.hbp.dialog.DetailEditDialog.DetailEditDialogListener;
import com.medicine.hbp.dialog.PhotographDialog.PhotographDialogListener;
import com.medicine.hbp.dialog.Loading;
import com.medicine.hbp.http.AppHttpCallBack;
import com.medicine.hbp.http.AppHttps;
import com.medicine.hbp.http.HttpInterface;
import com.medicine.hbp.mob.artGroupVo;
import com.medicine.hbp.pay.zfb.PayResult;
import com.medicine.hbp.sp.LoginSp;
import com.medicine.hbp.uitl.ChoosePicturesUtils;
import com.medicine.hbp.uitl.DesUtil;
import com.medicine.hbp.uitl.EncryUtils;
import com.medicine.hbp.uitl.NetWorkUtils;
import com.medicine.hbp.uitl.Share;
import com.medicine.hbp.uitl.StartIntent;
import com.medicine.hbp.uitl.ToastUtil;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.utils.Log;

/**
 *
 * @author wanghua
 *
 */
public class WebActivity extends BaseActivity {

	private int id;
	private String name = "";
	private WebView webView;
	private ImageView img_pinglun;
	private TextView btn_dialog;
	private TextView textView_jb;
	private Loading loading;
	private ImageView img_web_collection;
	private ImageView  nodate;
	private LinearLayout btn_webdeit;
	private boolean isCollect;
	private String url;
	private artGroupVo vo;
	private static final int SDK_PAY_FLAG = 1;
	private IWXAPI api;

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@SuppressWarnings("unused")
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case SDK_PAY_FLAG: {
					PayResult payResult = new PayResult((String) msg.obj);
					/**
					 * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
					 * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
					 * docType=1) 建议商户依赖异步通知
					 */
					String resultInfo = payResult.getResult();// 同步返回需要验证的信息

					String resultStatus = payResult.getResultStatus();
					// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
					if (TextUtils.equals(resultStatus, "9000")) {
						Toast.makeText(WebActivity.this, "支付成功", Toast.LENGTH_SHORT)
								.show();
					} else {
						// 判断resultStatus 为非"9000"则代表可能支付失败
						// "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
						if (TextUtils.equals(resultStatus, "8000")) {
							Toast.makeText(WebActivity.this, "支付结果确认中",Toast.LENGTH_SHORT).show();

						} else {
							// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
							Toast.makeText(WebActivity.this,"支付失败" + resultStatus + "-" + resultInfo,Toast.LENGTH_SHORT).show();

						}
					}
					break;
				}
				default:
					break;
			}
		}

		;
	};
	String Image="";
	@Override
	protected void onCreate(Bundle savedactivityState) {
		super.onCreate(savedactivityState);
		setContentView(R.layout.home_act);
		initTop();
		vo=(artGroupVo) getIntent().getSerializableExtra("vo");
		textView_jb = (TextView) findViewById(R.id.textView_jb);
		btn_webdeit = (LinearLayout) findViewById(R.id.btn_webdeit);
		webView = (WebView) findViewById(R.id.webView_act);
		btn_dialog = (TextView) findViewById(R.id.btn_dialog);
		img_pinglun = (ImageView) findViewById(R.id.img_pinglun);
		img_web_collection = (ImageView) findViewById(R.id.img_web_collection);
		nodate = (ImageView) findViewById(R.id.nodate);
//		webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		nodate.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				nodate.setVisibility(View.GONE);
				loading.showDialog();
				webView.loadUrl(url+"&token="+ LoginSp.getToken(aty)+"&type=app");
			}
		});
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String urls) {
				view.loadUrl(urls);
				return true;
			}
			@Override
			public void onPageFinished(WebView view, String urls) {
				super.onPageFinished(view, urls);
				if (!urls.contains(AppHttps.HTTP_URL
						+ HttpInterface.ART_DETAILS)) {
					btn_webdeit.setVisibility(View.GONE);
				} else {
					btn_webdeit.setVisibility(View.VISIBLE);
				}
				loading.dismissDialog();
			}
			@Override
			public void onReceivedError(WebView view, int errorCode,
										String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
				nodate.setVisibility(View.VISIBLE);
			}
		});

		WebSettings settings = webView.getSettings();
		// settings.setDomStorageEnabled(true);
		settings.setJavaScriptEnabled(true);
		settings.setJavaScriptCanOpenWindowsAutomatically(true);
		settings.setAllowFileAccess(true);// 设置允许访问文件数据
		// settings.setSupportZoom(true);
		// settings.setBuiltInZoomControls(true);
		settings.setJavaScriptCanOpenWindowsAutomatically(true);
		settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
		settings.setDatabaseEnabled(true);
		if(NetWorkUtils.getAPNType(aty)==0){
			settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
		}else{
			settings.setCacheMode(WebSettings.LOAD_DEFAULT);
		}
		webView.addJavascriptInterface(new JavaScriptInterface(), "obj");
		isCollect = getIntent().getBooleanExtra("isCollect", false);
		id = getIntent().getIntExtra("ID", 0);
		// webView.loadUrl("http://192.168.0.138:8080/medicine/api/article/artDetails.html?articleId=1");
		if (isCollect) {
			img_web_collection.setImageDrawable(getResources().getDrawable(
					R.mipmap.img_collection_yes));
		} else {
			img_web_collection.setImageDrawable(getResources().getDrawable(
					R.mipmap.img_collection_no));
		}
		webView.setWebChromeClient(new WebChromeClient());

//		if(vo!=null&&vo.artImg!=null&&vo.artImg.size()>0){
//			Image=vo.artImg.get(0).artImgUrl;
//		}
		if(vo!=null&&!TextUtils.isEmpty(vo.artImg)){
			Image=vo.artImg;
		}
		img_pinglun.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(vo!=null){
					if(TextUtils.isEmpty(LoginSp.getToken(aty))){
						StartIntent.startLogin(aty);
					}else{
						Share.openShare(WebActivity.this,String.valueOf(id),vo.artMsg,vo.artTitle,url,Image);
					}

				}else{

				}
			}
		});
		img_web_collection.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if(TextUtils.isEmpty(LoginSp.getToken(aty))){
					StartIntent.startLogin(aty);
				}else{
					if (isCollect) {
						httpDelCollect(id);
//						ToastUtil.showShort(WebActivity.this, "不能重复收藏");
					} else {
						httpSetCollec(id);
					}
				}
			}
		});
		loading = new Loading(aty);
		loading.showDialog();
		String time=getTime();
//		url = AppHttps.HTTP_URL + HttpInterface.ART_DETAILS + "?articleId="
//		+ id + "&date="+time+ "&appType=android" + "&appName=高血压" + "&token="
//		+ LoginSp.getToken(aty);

//		String des=DesUtil.crypt("artId="+ id + "&date="+time+ "&token="+ EncryUtils.getMD5String(id +""+time), "medicine", true);
//		Log.e("des",DesUtil.crypt(des, "medicine", false));
//		url =AppHttps.HTTP_URL + HttpInterface.ART_DETAILS + "?hashToken="+des+"&token="+ LoginSp.getToken(aty);

		String md5=EncryUtils.getMD5String(id +""+time+"medicine");
		url =AppHttps.HTTP_URL + HttpInterface.ART_DETAILS + "?hashToken="+md5+"&artId="+id+"&date="+time;
		webView.loadUrl(url+"&token="+ LoginSp.getToken(aty)+"&type=app");
		btn_dialog.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (LoginSp.getUserId(aty) != 0) {
					DetailEditDialog dialog = new DetailEditDialog(aty,
							new DetailEditDialogListener() {
								@Override
								public void onSelect(String content) {
									webView.loadUrl("javascript:addDiscuss('"+ LoginSp.getUserId(aty) + "','"+ content + "','"
											+ LoginSp.getUserName(aty) + "')");

								}

								@Override
								public void onCancel() {
								}
							});
					dialog.showDetailEditDialog();
				} else {
					StartIntent.startLogin(aty);
				}
			}
		});
		textView_jb.setVisibility(View.GONE);
		textView_jb.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(aty, ReportActivity.class);
				startActivity(intent);
				textView_jb.setVisibility(View.GONE);
			}
		});
		api = WXAPIFactory.createWXAPI(this, getResources().getString(R.string.wx_pay));
	}

	class JavaScriptInterface {
		@JavascriptInterface
		public void JavaScriptUserId(int userid) {
			if(TextUtils.isEmpty(LoginSp.getToken(aty))){
				StartIntent.startLogin(aty);
			}else{
				StartIntent.startUser(aty, userid);
			}

		}

		// @JavascriptInterface
		// public void JavaScriptPayZfb(String subject, String body, String
		// price) {
		// Log.e("js", subject + "-" + body + "-" + price);
		// httpZfb(subject, body, price);
		// }

		@JavascriptInterface
		public void JavaScriptPayBounty(String Bounty) {
			if(TextUtils.isEmpty(LoginSp.getToken(aty))){
				StartIntent.startLogin(aty);
			}else{
				startpayDialog(Bounty);

			}

		}
		@JavascriptInterface
		public void JavaScriptIntgNumber(String num) {
			ToastUtil.showShort(aty, num);
		}

		@JavascriptInterface
		public void JavaScriptPayZfb(String goodsId, String orderId) {
			if(TextUtils.isEmpty(LoginSp.getToken(aty))){
				StartIntent.startLogin(aty);
			}else{
//				startpayDialog(goodsId,orderId);

			}

		}
	}
	/**
	 * 调用相机拍照选择
	 */
	private void startpayDialog(final String Bounty) {
		Log.e("xxx",Bounty);
		PayDialog photographDialog = new PayDialog(aty,
				new PayDialogListener() {
					@Override
					public void onSelect(int position) {
						if (position == 0) {//支付宝
//							httpds(Bounty);
//							httpZfb02(goodsId, orderId);
							httpds(Bounty,"zfb");
						} else {//微信
							httpds(Bounty,"wx");
						}
					}
					@Override
					public void onCancel() {
					}
				});
		photographDialog.showPayDialog();
	}

	private void initTop() {
//		name = getIntent().getStringExtra("NAME");
		TopView topview = (TopView) findViewById(R.id.topview);
		topview.setTitle("");
		topview.setLeftVisibility(View.GONE);
		topview.setTitleColor(getResources().getColor(R.color.black));
		topview.setRightImageResource(R.mipmap.more);
		topview.setLeftVisibilityExit(View.VISIBLE);
		topview.setRightVisibility(View.VISIBLE);
		topview.setLeftImageResource(R.drawable.leftarrow);
		topview.setRightImagePadding(20, 0, 20, 0);
		topview.setLeftOnClickExit(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		topview.setRightOnClick(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (textView_jb.getVisibility() == View.GONE) {
					textView_jb.setVisibility(View.VISIBLE);
				} else {
					textView_jb.setVisibility(View.GONE);
				}
			}
		});
	}

	/**
	 * 对文章进行收藏
	 */
	private void httpSetCollec(int id) {
		HttpParams params = new HttpParams();
		params.put("artId", id);// 所属文章ID
		AppHttps.HttpPost(this, HttpInterface.SET_COLLEC, params,
				new AppHttpCallBack<Object>(Object.class, this) {
					@Override
					public void onSuccess(Object result) {
						ToastUtil.showShort(WebActivity.this, "文章收藏成功");
						isCollect = true;
						img_web_collection.setImageDrawable(getResources()
								.getDrawable(R.mipmap.img_collection_yes));
					}

					@Override
					public void onFailures(int errorCode, String errorMsg) {
						ToastUtil.showShort(WebActivity.this, errorMsg);
					}
				});
	}

	/**
	 * 取消收藏接口
	 */
	private void httpDelCollect(int id) {
		HttpParams params = new HttpParams();
		params.put("artId", id);// 所属文章ID
		AppHttps.HttpPost(this, HttpInterface.DEL_COLLECT, params,
				new AppHttpCallBack<Object>(Object.class, this) {
					@Override
					public void onSuccess(Object result) {
						isCollect = false;
						img_web_collection.setImageDrawable(getResources()
								.getDrawable(R.mipmap.img_collection_no));
						ToastUtil.showShort(aty, "取消收藏成功");
					}

					@Override
					public void onFailures(int errorCode, String errorMsg) {
						ToastUtil.showShort(aty, errorMsg);
					}
				});
	}

//	private void httpZfb02(String goodsId, String orderId) {
//		HttpParams params = new HttpParams();
//		params.put("body", goodsId);// 商品详情
//		params.put("price", orderId);// 商品金额
//		AppHttps.HttpPost(this, HttpInterface.CONFIRM_ORDER, params,
//				new AppHttpCallBack<Object>(Object.class, aty) {
//					@Override
//					public void onSuccess(String t) {
//						super.onSuccess(t);
//						String pay = t.replace("{'key':'", "");
//						pay = pay.replace("'}", "");
//						ZfbRunnable(pay);
//					}
//
//					@Override
//					public void onSuccess(Object result) {
//					}
//
//					@Override
//					public void onFailures(int errorCode, String errorMsg) {
//					}
//				});
//	}

	private void httpds(String goodsId,final String payType) {
		HttpParams params = new HttpParams();
		params.put("bountyId", goodsId);// 打赏订单ID
		params.put("type", payType);
		AppHttps.HttpPost(this, HttpInterface.CONFIRM_BOUNTY, params,
				new AppHttpCallBack<Object>(Object.class, aty) {
					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);
						JSONObject json;
						try {
							json = new JSONObject(t);
							if(payType.equals("zfb")){
								String pay = t.replace("{'key':'", "");
								pay = pay.replace("'}", "");
								ZfbRunnable(pay);
//								ZfbRunnable(zfbPay(json));
							}else{
								PayReq req = new PayReq();
								// req.appId = "wxf8b4f85f3a794e77"; // 测试用appId
								req.appId = json.getString("appid");
								req.partnerId = json.getString("partnerid");
								req.prepayId = json.getString("prepayid");
								req.nonceStr = json.getString("noncestr");
								req.timeStamp = json.getString("timestamp");
								req.packageValue = json.getString("package");
								req.sign = json.getString("sign");
								// req.extData = "app data"; // optional
								// 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
								api.sendReq(req);
							}

						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

//						String pay = t.replace("{'key':'", "");
//						pay = pay.replace("'}", "");
//						ZfbRunnable(pay);
					}

					@Override
					public void onSuccess(Object result) {
					}

					@Override
					public void onFailures(int errorCode, String errorMsg) {
					}
				});
	}

	/**
	 * 支付
	 */
	private void httpPay(final String payType) {
		HttpParams params = new HttpParams();
		params.put("title", "title");
		params.put("type", payType);
		params.put("body", "body");
		params.put("price", 20);
		AppHttps.HttpPost(this, HttpInterface.PAY_SIGN, params,
				new AppHttpCallBack<Object>(Object.class, aty) {
					@Override
					public void onSuccess(String t) {
						// TODO Auto-generated method stub
						super.onSuccess(t);

						Log.e("json",t);

					}

					@Override
					public void onFailures(int errorCode, String errorMsg) {
						// ToastUtil.showShort(aty, errorMsg);
					}

					@Override
					public void onSuccess(Object result) {
					}
				});

	}

	/**
	 *
	 * @param payInfo签名参数
	 */
	public void ZfbRunnable(final String payInfo) {
		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(WebActivity.this);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo, true);

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	public String getTime(){
		return new SimpleDateFormat("yyyyMMdd").format(new Date());
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
	}
	private String zfbPay(	JSONObject json){
		try {
			String pay="sign="+json.getString("sign")+
					"&body="+json.getString("body")+
					"&_input_charset="+json.getString("_input_charset")+
					"&it_b_pay="+json.getString("it_b_pay")+
					"&total_fee="+json.getString("total_fee")+
					"&subject="+json.getString("subject")+
					"&sign_type="+json.getString("sign_type")+
					"&service="+json.getString("service")+
					"&notify_url="+json.getString("notify_url")+
					"&seller_id="+json.getString("seller_id")+
					"&partner="+json.getString("partner")+
					"&out_trade_no="+json.getString("out_trade_no")+
					"&payment_type="+json.getString("payment_type")+
					"&return_url="+json.getString("return_url");
			return pay;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "";

	}
}
